package com.zyh.study.ForestPlus;

import com.dtflys.forest.Forest;
import com.dtflys.forest.backend.ContentType;
import com.dtflys.forest.config.ForestConfiguration;
import com.zyh.study.ForestPlus.config.AlpacaConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.Base64;

/**
 * alpaca消息监听实现
 *
 * @author Lunyue Chen
 */
@Component
public class AlpacaMessageListener {

    private ForestConfiguration forestConfig = Forest.config();

    public static final String ACCEPT = "accept";
    public static final String AUTHORIZATION = "authorization";

    @Autowired
    private AlpacaConfig config;

    // 预构建Basic Auth认证头
    String credentials = config.getBrokerApiKey() + ":" + config.getBrokerApiSecret();
    String authHeader = "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes());

    /**
     * 订阅交易事件
     * 查询历史事件，需传入范围，当达到until则将结束
     * 若指定了 until，则必须指定 since
     * 若指定了 until_id，则必须指定 since_id
     * 若指定了 until_ulid，则必须指定 since_ulid
     * since、since_id 和 since_ulid 不能同时使用
     * 如果未指定since、since_id或since_ulid，则不会返回任何历史数据
     * 达到until_ulid后，流将结束（状态码200）
     *
     * @return
     */
    public void subscribeToTradingActivities(LocalDate since, LocalDate until, String sinceId, String untilId, AlpacaSseDeal sse) {
        String url = "https://broker-api.sandbox.alpaca.markets/v2/events/trades";
        Forest.get(url)
                .addQuery("since", since)
                .addQuery("until", until)
                .addQuery("since_id", sinceId)
                .addQuery("until_id", untilId)
                .addHeader(ACCEPT, "text/event-stream")
                .addHeader(AUTHORIZATION, authHeader)
                .maxRetryCount(3)
                .maxRetryInterval(100L)
                .sse()
                .setOnOpen(sse::onSSEOpen)
                .setOnClose(sse::onSSEClose)
                .addOnData(sse::onMessage)
                .asyncListen();
    }

    /**
     * 订阅非交易事件
     * 若指定了 until（时间），则 since（时间）为必填项
     * 若指定了 until_id，则 since_id 为必填项
     * 若指定了 until_uid，则 since_uid 为必填项
     * since、since_id 和 since_uid 不能同时使用
     * @param since
     * @param until
     * @param sinceId
     * @param untilId
     * @param sse
     */
    public void subscribeToNonTradingActivities(String id, LocalDate since, LocalDate until, Integer sinceId, Integer untilId,
                                                String sinceUlid, String untilUlid, Boolean includePreprocessing, String groupId, AlpacaNonSseDeal sse) {
        String url = "https://broker-api.sandbox.alpaca.markets/v1/events/nta";
        Forest.get(url)
                .addQuery("id", id)
                .addQuery("since", since)
                .addQuery("until", until)
                .addQuery("since_id", sinceId)
                .addQuery("until_id", untilId)
                .addQuery("since_ulid", sinceUlid)
                .addQuery("until_ulid", untilUlid)
                .addQuery("include_preprocessing", includePreprocessing)
                .addQuery("group_id", groupId)
                .addHeader(ACCEPT, ContentType.APPLICATION_JSON)
                .addHeader(AUTHORIZATION, authHeader)
                .maxRetryCount(3)
                .maxRetryInterval(100L)
                .sse()
                .setOnOpen(sse::onSSEOpen)
                .setOnClose(sse::onSSEClose)
                .addOnData(sse::onMessage)
                .asyncListen();
    }


    // 实现alpaca消息监听


}
